package com.juzipi.demo.handler;

import com.alibaba.fastjson.JSON;
import com.juzipi.demo.tools.Result;
import com.juzipi.demo.tools.ResultTool;
import com.juzipi.demo.utils.JsonAuthentication;
import com.juzipi.demo.utils.ResultCode;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录失败处理
 */

@Component
public class MyAuthenticationFailureHandler extends JsonAuthentication implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Result result = null;
        //账号已过期异常
        if (e instanceof AccountExpiredException){
            result = ResultTool.failCustomize(ResultCode.USER_ACCOUNT_EXPIRED, null);
        }
        //密码已过期异常
        else if (e instanceof BadCredentialsException){
            result = ResultTool.failCustomize(ResultCode.USER_PASSWORD_ERROR,null);
        }
        //账号不可用
        else if (e instanceof DisabledException){
            result = ResultTool.failCustomize(ResultCode.USER_ACCOUNT_DISABLE,null);
        }
        //账号锁定
        else if (e instanceof LockedException){
            result = ResultTool.failCustomize(ResultCode.USER_ACCOUNT_LOCKED,null);
        }
        //用户不存在
        else if (e instanceof InternalAuthenticationServiceException){
            result = ResultTool.failCustomize(ResultCode.USER_ACCOUNT_NOT_EXIST,null);
        }
//        String jsonString = JSON.toJSONString(result);
//        //防止乱码
//        httpServletResponse.setContentType("text/json;charset=utf-8");
//        //放入response中返回
//        httpServletResponse.getWriter().write(jsonString);
        this.WriteJson(httpServletRequest,httpServletResponse,result);
    }
}
